<?php
/**
 * Ly - 核心标签类
 *
 * 所有扩展标签类的父类，提供必要的标签解析功能
 *
 * Copyright (c) 2013 YinHailin All rights reserved.
 * @Author: YinHailin
 * @Authorize: Boren Network
 * @Created by YinHailin at 2013-11-01
 */

defined('LY_VERSION') or exit();

abstract class Taglib {

  /* 标签列表 */
  protected $Tags = array();

  /* 模板对象 */
  protected $TempEngine;

  /* 构造方法 */
  public function __construct() {
    $this->TempEngine = LyCore::Instance('TemplateCore');
  }

  /*
   * XML属性解析
   + 将传递的字符串作为XML的属性进行分析
   * @param string $attr XML属性字符串
   * @param string $tag 标签
   * @return array
   */
  public function ParseXmlAttr($attr, $tag) {
    $filterTrue = array('&', '>', '<');
    $filterFalse = array('*and*', '*gt*', '*lt*');
    $tag = strtolower($tag);
    //XML安全过滤
    $attr = str_replace($filterTrue, $filterFalse, $attr);
    $xml = '<tpl><tag '.$attr.' /></tpl>';
    $xml = simplexml_load_string($xml);
    if (!$xml) {
      halt('XML标签属性有误', __FILE__, __LINE__);
    } else {
      $args = (array)($xml->tag->attributes());
      $args = array_change_key_case($args['@attributes'], CASE_LOWER);
      $attrs = explode(',', $this->Tags[$tag]['attr']);
      foreach ($attrs as $value) {
        $value = trim($value);
        if (isset($args[$value])) {
          $args[$value] = str_replace($filterFalse, $filterTrue, $args[$value]);
        }
      }
      return $args;
    }
  }

  /*
   * 自动构建变量
   * @param string $var 变量字符串
   * @return string
   */
  public function AutoBuildVar($var) {
    if (strpos($var, '.')) {
      //点语法数组
      if (substr($var, 0, 1) == '$') { $var = substr($var, 1);}
      $varArray = explode('.', $var);
      $var = '$'.array_shift($varArray);
      if (count($varArray)) {
        foreach ($varArray as $value) {
          if (strpos($value, '$') === 0) {
            $var .= '['.$value.']';
          } else {
            $var .= '[\''.$value.'\']';
          }
        }
      }
    } elseif (!defined($var) && substr($var, 0, 1) != '$') {
      //非常量则添加变量符
      $var = '$'.$var;
    }
    return $var;
  }

  /*
   * 获取标签列表
   * @return array
   */
  public function GetTags() {
    return $this->Tags;
  }
}